package com.smart.common.utils.file;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.util.Arrays;
import org.apache.poi.util.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.smart.common.config.SmartConfig;
import com.smart.common.constant.Constants;
import com.smart.common.utils.StringUtils;
import org.springframework.mock.web.MockMultipartFile;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;

/**
 * 图片处理工具类
 *
 * @author smart
 */
public class ImageUtils
{
    private static final Logger log = LoggerFactory.getLogger(ImageUtils.class);

    public static byte[] getImage(String imagePath)
    {
        InputStream is = getFile(imagePath);
        try
        {
            return IOUtils.toByteArray(is);
        }
        catch (Exception e)
        {
            log.error("图片加载异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(is);
        }
    }

    public static InputStream getFile(String imagePath)
    {
        try
        {
            byte[] result = readFile(imagePath);
            result = Arrays.copyOf(result, result.length);
            return new ByteArrayInputStream(result);
        }
        catch (Exception e)
        {
            log.error("获取图片异常 {}", e);
        }
        return null;
    }

    /**
     * 读取文件为字节数据
     * 
     * @param url 地址
     * @return 字节数据
     */
    public static byte[] readFile(String url)
    {
        InputStream in = null;
        try
        {
            if (url.startsWith("http"))
            {
                // 网络地址
                URL urlObj = new URL(url);
                URLConnection urlConnection = urlObj.openConnection();
                urlConnection.setConnectTimeout(30 * 1000);
                urlConnection.setReadTimeout(60 * 1000);
                urlConnection.setDoInput(true);
                in = urlConnection.getInputStream();
            }
            else
            {
                // 本机地址
                String localPath = SmartConfig.getProfile();
                String downloadPath = localPath + StringUtils.substringAfter(url, Constants.RESOURCE_PREFIX);
                in = new FileInputStream(downloadPath);
            }
            return IOUtils.toByteArray(in);
        }
        catch (Exception e)
        {
            log.error("获取文件路径异常 {}", e);
            return null;
        }
        finally
        {
            IOUtils.closeQuietly(in);
        }
    }

    /**
     * 与图片类与文件上传类转换
     * @param image     文件类
     * @param filename  文件名称
     * @return
     * @throws IOException
     */
    public static MultipartFile bufferedImageToMultipartFile(BufferedImage image, String filename) throws IOException {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(image, "jpg", baos); // 使用png格式，也可以根据需要改为其他格式
        byte[] imageBytes = baos.toByteArray();
        ByteArrayInputStream bais = new ByteArrayInputStream(imageBytes);

        return new MockMultipartFile("file", filename, "image/png", bais);
    }

    /**
     * 文件上传类与图片类转换
     * @param file 文件类
     * @return
     * @throws IOException
     */
    public static BufferedImage multipartFileToBufferedImage(MultipartFile file) throws IOException {
        // 将MultipartFile转换为字节数组
        BufferedImage image = ImageIO.read(file.getInputStream());
        return image;

    }

    /**
     * 压缩
     * @return
     */
    public static BufferedImage compressImage() {
        try {
            // 读取原始图片
            BufferedImage originalImage = ImageIO.read(new File("D:\\a.jpg"));

            // 设置缩略图的宽度和高度
            int thumbnailWidth = 1024;
            int thumbnailHeight = 1024;

            // 创建缩略图
            BufferedImage thumbnailImage = createThumbnail(originalImage, thumbnailWidth, thumbnailHeight);

            // 保存缩略图
//            ImageIO.write(thumbnailImage, "jpg", new File("aT.jpg"));
            return thumbnailImage;
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }

    /**
     * 压缩图片
     * @param originalImage
     * @param thumbWidth
     * @param thumbHeight
     * @return
     */
    public static BufferedImage createThumbnail(BufferedImage originalImage, int thumbWidth, int thumbHeight) {
        // 计算缩放比例
        double scale = Math.min((double) thumbWidth / originalImage.getWidth(), (double) thumbHeight / originalImage.getHeight());

        // 新建缩略图大小
        int newWidth = (int) (originalImage.getWidth() * scale);
        int newHeight = (int) (originalImage.getHeight() * scale);

        Image thumbnail = originalImage.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);

        // 创建新的缩略图
        BufferedImage newImage = new BufferedImage(newWidth, newHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = newImage.createGraphics();
        graphics2D.drawImage(thumbnail, 0, 0, null);
        graphics2D.dispose();

        return newImage;
    }
}
